import React from "react";
import { renderToString } from "react-dom/server";
import { StaticRouter } from 'react-router-dom/server';
// react-router-dom 版本 6 中，StaticRouter 被移到了 react-router-dom/server 模块中, 否则 react-router-dom 模块
import { Provider } from 'react-redux';
import serialize from 'serialize-javascript';
import App from "../views/app";
import configureStore from '../store';

export default req => {

  const store = configureStore();
  const preloadedState = store.getState();

  const content = renderToString(
    <Provider store={store}>
      <StaticRouter location={req.url}>
        <App />
      </StaticRouter>
    </Provider>
  );
  return `
    <html>
      <head>
        <title>react ssr</title>
      </head>
      <body>
        <div id="root">${content}</div>
        <script>
          window.__PRELOADED_STATE__ = ${serialize(preloadedState)}
        </script>
        <script src="bundle.js"></script>
      </body>
    </html>
  `;
};